package org.ucas.faker.web.dao;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import org.ucas.faker.web.entity.Depot;

import java.util.List;

@Repository
public interface DepotDao extends PagingAndSortingRepository<Depot,Long> {

  @Query("SELECT d FROM Depot d WHERE d.owner = ?1 AND d.deleted = false")
  public List<Depot> findByOwner(long userId);

  @Modifying
  @Query("UPDATE Depot d SET d.deleted = true  WHERE d.id = ?1")
  public void deleteById(long depotId);

  @Modifying
  @Query("DELETE FROM Depot d WHERE d.id = ?1")
  public void destroy(long depotId);

  @Query("SELECT d FROM Depot d WHERE d.owner = ?1 AND d.deleted = false")
  public Page<Depot> pageByOwner(long userId, Pageable pageable);

  @Query("SELECT d FROM Depot d WHERE d.deleted = false")
  public Page<Depot> pageAll(Pageable pageable);

  @Query("SELECT d FROM Depot d WHERE d.owner = ?1 AND d.name = ?2")
  public Depot findByOwnerAndName(long owner, String name);

  @Modifying
  @Query("UPDATE Depot d SET d.version = d.version + 1 WHERE d.id = ?1")
  public void incVersion(long depotId);

  @Query("SELECT d.version FROM Depot d WHERE d.id = ?1")
  public long curVersion(long depotId);
}
